<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-if="open" v-model="open" width="1300px" append-to-body>
    <div v-loading="loading">
      <el-form ref="form" :rules="rules" :model="form" label-width="130px" :inline="true" :disabled="disabledEdit">
        <el-form-item label="跟进方式:" prop="followTypeDictValue">
          <el-select v-model="form.followTypeDictValue" clearable reserve-keyword placeholder="请选择跟单方式">
            <el-option v-for="dict in follow_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="进展阶段:" prop="followStageId">
          <el-select v-model="form.followStageId" placeholder="请选择进展阶段" @change="stageChange" clearable>
            <el-option-group v-for="(group, index) in followStage" :key="index" :label="group.followTypeName" >
              <el-option v-for="item in group.jzgFollowStageVoList" :key="item.id" :label="item.name" :value="item.id">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                  {{ item.progressCoefficient }}
                </span>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="成交系数:" prop="transactionCoefficient">
          <el-rate v-model="form.transactionCoefficient"  style="transform: scale(1.2);margin-left: 10px;"/>
          <span style="font-size: 16px; color: #409eff; padding-left: 20px"
            >周期：<span>{{ cycle }}天</span></span
          >
        </el-form-item>
        <el-form-item label="预计成交时间" prop="estimatedBuyDate">
          <!-- <el-date-picker
            v-model="estimatedBuyDate"
            style="width: 240px"
            value-format="YYYY-MM-DD"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker> -->
          <el-date-picker
              style="width: 116px!important"
              v-model="form.estimatedBuyDateStart"
              disabled
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
              placeholder="开始时间"
            ></el-date-picker>
             ~ 
            <el-date-picker
              style="width: 116px!important"
              v-model="form.estimatedBuyDateEnd"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
              placeholder="结束时间"
            ></el-date-picker>
        </el-form-item>
        <el-form-item label="客户名称:" prop="supplierId">
          <el-select disabled @change="customerChange" v-model="form.supplierId" clearable reserve-keyword placeholder="请选择客户名称">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人:" prop="contacts">
          <el-select @change="contacChange" v-model="form.contacts" filterable clearable remote reserve-keyword placeh :loading="loading">
            <el-option v-for="item in contactsOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="岗位:" prop="postName">
          <el-input disabled v-model="form.postName"></el-input>
        </el-form-item>
        <el-form-item label="预计成交金额:" prop="estimatedTransactionAmount">
          <el-input v-model="form.estimatedTransactionAmount" type="number"></el-input>
        </el-form-item>
        <el-form-item label="跟单人:" prop="followUserId">
          <el-select disabled v-model="form.followUserId" filterable clearable remote reserve-keyword placeholder="请选择跟单人" :loading="loading">
            <el-option v-for="item in userList" :key="item.value" :label="item.realityName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="协助人:" prop="assistUserId">
          <el-input v-model="form.assistUserId" v-show="false" placeholder="" size="normal" clearable></el-input>

          <el-select disabled multiple v-model="assistUserIds" value-key="" placeholder="请选择协助人" clearable filterable @change="changeAssist">
            <el-option v-for="item in userList" :key="item.userId" :label="item.realityName" :value="item.userId + ''"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预计毛利:" prop="delayDays">
          <el-input v-model="form.delayDays" @change="handleDelayChange(form)"></el-input>
        </el-form-item>
        <el-form-item label="跟进时间:" prop="followDate">
          <el-date-picker
            v-model="form.followDate"
            style="width: 240px"
            value-format="YYYY-MM-DD hh:mm:ss"
            type="date"
            placeholder="选择跟进时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="跟单内容:" prop="comment">
          <el-input @focus="commentFocus" @blur="isFocused = false" type="textarea" style="width: 1050px" :rows="9" v-model="form.comment">
          </el-input>
          <div v-if="!form.comment && !isFocused" class="custom-placeholder">
            <p>
              <span class="placeholder-title">讨论内容</span><br/>
            <span class="placeholder-content">主要话题：详细列出本次跟进中讨论的各个主要话题</span>
            </p>
            <p>
              <span class="placeholder-title">客户问题</span><br/>
            <span class="placeholder-content">记录客户在本次提出的所有问题，明确具体需求和期望</span>
            </p>
            <p>
              <span class="placeholder-title">解决方案</span><br/>
            <span class="placeholder-content">详细描述为客户提出的解决方案或建议，并记录客户反馈</span>
            </p>
          </div>
        </el-form-item>
        <el-form-item v-if="!isContract" label="下一步计划时间:" label-width="130px" prop="nextPlanDate">
          <el-date-picker
            v-model="form.nextPlanDate"
            style="width: 240px"
            value-format="YYYY-MM-DD hh:mm:ss"
            type="date"
            placeholder="选择时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-if="!isContract" label="下一步推进内容:" prop="nextComment">
          <el-input type="textarea" style="width: 1050px" :rows="4" v-model="form.nextComment"></el-input>
        </el-form-item>
        <el-row>
          <el-form-item label="附件:">
            <el-upload
              style="width: 300px"
              class="upload-demo"
              drag
              v-model:file-list="fileList"
              show-file-list
              :headers="headers"
              :on-success="(res, file) => handleUploadSuccess(res, file, 'annex')"
              :on-error="handleError"
              :action="uploadUrl"
              multiple
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽或 <em>点击上传</em></div>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading" v-show="!disabledEdit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import modelMixin from '@/mixins/modelMixin';
import { listUser } from '@/api/system/user';
import { allListByType,listByTypeId } from '@/api/goods/followStage';
import { getSupplier } from '@/api/goods/supplier';
import clue from '@/api/goods/clue';
import { addFollowOrder } from '@/api/goods/followOrder';
import { formatDate } from '@/utils/index';
import { globalHeaders } from '@/utils/request';
import moment from 'moment';
export default {
  name: 'addForm',
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      uploadUrl: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload', // 上传的图片服务器地址
      fileList: [],
      headers: globalHeaders(),
      title: '',
      funcObj: clue,
      isFocused: false,

      form: {},
      supplierOptions: [], //客户
      contactsOptions: [], //联系人
      active: 1,
      baseInput: 200,
      data: [],
      dateRange: [],
      dataSource: [],
      loading: false,
      followStage: [], //跟单阶段
      follow_type: [], //跟单方式
      stop_reson: [], //断续原因
      userList: [], //跟单人列表
      follow_stage: [], //跟单状态
      followStatusDictValue: '',
      disabledEdit: false,
      supplierDisabled: false,
      assistUserIds: [], //协助人
      estimatedBuyDate: [],
      followStatus: [], //跟单状态
      cycle:'',
      followTypes: [
        { label: '当面拜访', value: 1 },
        { label: '跟进', value: 2 },
        { label: '续费', value: 3 }
      ],
      rules: {
        followTypeDictValue: [{ required: true, message: '跟单方式不能为空', trigger: 'blur' }],
        followUserId: [{ required: true, message: '跟单人不能为空', trigger: 'blur' }],
        followDate: [{ required: true, message: '跟单时间不能为空', trigger: 'blur' }],
        followStageId: [{ required: true, message: '跟单阶段不能为空', trigger: 'blur' }],
        contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        payAmount: [{ required: true, message: '续费金额不能为空', trigger: 'blur' }],
        nextComment: [{ required: true, message: '下一步推进内容不能为空', trigger: 'blur' }],
        nextPlanDate: [{ required: true, message: '下一步计划时间不能为空', trigger: 'blur' }],
        comment: [{ required: true, message: '跟单内容不能为空', trigger: 'blur' }],
        transactionCoefficient: [{ required: true, message: '成交系数不能为空', trigger: 'blur' }]
      }
    };
  },
  computed: {
    isContract() {
      let item = this.followStatus.find((v) => v.id == this.form.followStageId);
      return item && item.stageProcess
    },

  },
  methods: {
    async edit(row) {
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.open = true;
      this.title = '跟进进度';
      this.form = {};
      this.followStatusDictValue = '';
      this.dataSource = [];
      this.getDicts(['follow_type', 'stop_reson', 'follow_stage']);
      await this.getDetail(row);
      this.listSysUser();
      this.getAll();
      this.getFollowStatus(this.form.followTypeId);

      this.supplierDisabled = true;
    },
    view(row) {
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.form = {};
      this.followStatusDictValue = '';
      this.open = true;
      this.disabledEdit = true;
      this.title = '跟单详情';
      this.form = row;
      this.getDicts(['follow_type', 'stop_reson', 'follow_stage']);
      this.listSysUser();
      listFollowStage().then((res) => {
        this.followStage = res.rows.sort((a, b) =>{
          const getNum = (val)=>{
            return +(val.replace('%',''))
          }
          return getNum(a.progressCoefficient) - getNum(b.progressCoefficient);
        });

        this.detailAfter();
      });
    },
    cancel() {
      this.open = false;
    },
    getFollowStatus(id) {
      listByTypeId(id)
       .then((res) => {
          this.followStatus = res || [];
        })
       .catch((error) => {
          console.error(error);
        });
    },
    getAll() {
      allListByType().then((res) => {
        this.followStage = (res || []).filter((item) => item.followTypeId == this.form.followTypeId).map(v=>{
          v.jzgFollowStageVoList.sort((a, b) =>{
            const getNum = (val)=>{
              return +(val.replace('%',''))
            }
            return getNum(a.progressCoefficient) - getNum(b.progressCoefficient);
          });
          return v;
        })
      console.log('this.followStage',this.followStage);
      });

    },
    // 上传成功
    handleUploadSuccess(res, file, key) {
      // 如果上传成功
      if (res.code == 200) {
        this.form[key] = res.data.url;
      } else {
        this.$modal.msgError(res.msg);
      }
    },
    hanldeFollowStageChange(id) {
      var followStageData = this.followStage.find(function (obj) {
        return obj.id == id;
      });
      if (followStageData) {
        this.followStatusDictValue = followStageData.stageName;
      }
    },
    handleSelectionChange(val) {
      this.multiple = val.length > 1;
    },
    selectHandle(row) {
      return 1;
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },

    remoteMethod(query, listKey, key) {
      const optionKey = listKey + 'Options';
      if (query !== '') {
        this[optionKey] = this[listKey + 'List'].filter((item) => {
          return item[key].toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this[optionKey] = this[listKey + 'List'];
      }
    },
    customerChange(value) {
      if (!value) return;

      getSupplier(value).then((res) => {
        if (res.data.supplierContactList.length > 0) {
          this.contactsOptions = res.data.supplierContactList;
        } else {
          this.form.contacts = '';
          this.contactsOptions = [];
        }
      });
    },
    // 联系人变更
    contacChange(value) {
      let item = this.contactsOptions.find((item) => item.id == value);
      this.form.postName = (item && item.postName) || '';
      console.log('this.form :>> ', this.form);
    },
    listSysUser() {
      listUser()
        .then((res) => {
          this.userList = res.rows;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    classifyForm() {
      this.form.clueId = this.form.id;
      this.form.payOrderDetailId = 0;
      delete this.form.id;
      this.form.annex = this.fileList.map((item) => item.response.data.url).join(',');
    },
    detailAfter() {
      this.hanldeFollowStageChange(this.form.followStageId);
    },    
    /**
     * 计算周期
     */
    calcCycle(info) {
      console.log(info, 'form');
      if(info.jzgFollowStageVoList && info.jzgFollowStageVoList.length > 0){
        let item = info.jzgFollowStageVoList.find((v) => v.id == info.followStageId);
        if (item) {
          let endDate = item.progressCoefficient == '100%' ? moment(info.orderFollowDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD');
          let starDate = moment(info.followDate).format('YYYY-MM-DD');
          console.log('777',777);
          return moment(endDate).diff(starDate, 'days') + 1;
        }
      }

      return '';
    },
    getDetail(row) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        this.funcObj
          .get(row.id)
          .then((res) => {
            this.loading = false;
            if (res.code == 200) {
              this.form = JSON.parse(JSON.stringify(res.data || {}));
              this.form.payAmount = 0;
              this.assistUserIds = (this.form.assistUserId || '').split(',');
              this.form.followStageId = '';
              this.form.followDate = moment().format('YYYY-MM-DD HH:mm:ss');
              this.form.estimatedBuyDateEnd = ''
              console.log('this.form :>> ', this.form);
              this.cycle = this.calcCycle(res.data);
              if (typeof this.detailAfter === 'function') {
                this.detailAfter();
              }
              this.customerChange(this.form.supplierId);
              resolve();
            } else {
              this.$modal.msgError(res.msg);
              reject();
            }
          })
          .catch((err) => {
            this.loading = false;
            console.log('err :>> ', err);
            reject();
          });
      });
    },
    handleDelayChange(row) {
      let date = row.endDate;
      date = Date.parse(new Date(date)) / 1000; // 转换成时间戳，返回值是ms，除1000后转化成秒
      date += 86400 * row.delayDays; // 一天是86400秒
      let newDate = new Date(parseInt(date) * 1000); // 把时间戳转换成日期
      //这步就是给所需变化的值赋值
      row.delayDate = formatDate(newDate);
    },
    handleDelayDateChange(row) {
      let date1 = Date.parse(new Date(row.endDate));
      let date2 = Date.parse(new Date(row.delayDate));
      row.delayDays = parseInt(Math.abs(date2 - date1) / 1000 / 86400);
    },
    commentFocus(){
      this.isFocused = true
      if(!this.form.comment){
        this.form.comment = '讨论内容：\n\n\n客户问题：\n\n\n解决方案：'
      }
    },
    // 是是否到了合同阶段
    
    stageChange(e){
      console.log(e);
      console.log('this.followStage',this.followStage);
      let item = this.followStage[0].jzgFollowStageVoList.find(item => item.id == e)
      console.log('item :>> ', item)
      if(item) this.form.stageCycle = item.stageCycle
      else this.form.stageCycle = ''
    },
    //提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          typeof this.classifyForm === 'function' && this.classifyForm();
          this.loading = true;
          addFollowOrder(this.form)
            .then((res) => {
              this.loading = false;
              if (res.code == 200) {
                this.$modal.msgSuccess('新增成功');
                if (close) {
                  this.open = false;
                }
                console.log('this.form',this.form);
                this.$emit('ok',this.form);
              } else {
                this.$modal.msgError(res.msg);
              }
            })
            .catch((err) => {
              console.log('err :>> ', err);
              this.loading = false;
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.custom-placeholder {
  position: absolute;
  top: -10px;
  left: 11px;
  pointer-events: none;
  font-size: 14px;
  line-height: 1.5;
}

.placeholder-title {
  color: #303133;
  font-weight: 500;
}

.placeholder-content {
  color: #909399;
}

:deep(.el-textarea__inner) {
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-textarea__inner::placeholder) {
  color: transparent;
}
</style>